package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class IWmChannelServiceimpl extends ServiceImpl<WmChannelMapper,WmChannel> implements IWmChannelService {
    @Override
    public ResponseResult listByName(ChannelDto channelDto) {
        // 根据频道名称分页查询列表
        // 构建分页条件
       IPage<WmChannel> page=new Page<>(channelDto.getPage(),channelDto.getSize());
        // 构建查询条件
        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
        // 判断频道名称是否为空,不为空,添加查询条件
        if (!StringUtils.isEmpty(channelDto.getName())){
            query.like(WmChannel::getName,channelDto.getName());
        }
        // 执行分页查询
        IPage<WmChannel> iPage = this.page(page, query);
        long total = iPage.getTotal();
        List<WmChannel> records = iPage.getRecords();
        // 构建通用的分页响应
        PageResponseResult result=new PageResponseResult(channelDto.getPage(),channelDto.getSize(),total,records);

        return result;
    }

    /**
     * 频道新增
     * @param channel
     * @return
     */
    @Override
    public ResponseResult saveWmChannel(WmChannel channel) {
        //判断参数是否为空
        if (channel==null || StringUtils.isEmpty(channel.getName())){
            //返回错误提示
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存新增的频道
        //查询频道名称是否已存在
        //根据名称查询
        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
        query.eq(WmChannel::getName,channel.getName());
        int count = this.count(query);
        if (count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //创建时间
        channel.setCreatedTime(new Date());
        this.save(channel);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateChannel(WmChannel wmChannel) {
        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
        query.eq(WmChannel::getName,wmChannel.getName());
        int count = this.count(query);
        if (count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        this.updateById(wmChannel);

        return ResponseResult.okResult();
    }
}
